
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net.Sockets;

using Logis.Utility.Log;
namespace InTelReceiver
{
    class TIClientSession
    {

        public string strName = "";
        public bool m_bNamed = false;

        TcpClient m_tcp;
        NetworkStream m_ns;

        byte[] m_bary = new byte[500];
        int m_nIndex = 0;

        public TIClientSession(TcpClient arg_tc)
        {
            m_tcp = arg_tc;
            m_tcp.SendTimeout = 1500;
            m_ns = m_tcp.GetStream();
            strName = arg_tc.Client.RemoteEndPoint.ToString();
            m_bNamed = true;
        }

        public void send(string arg_strCmd)
        {
            try
            {
                byte[] bary = System.Text.Encoding.Default.GetBytes(arg_strCmd);
                m_ns.Write(bary, 0, bary.Length);
                m_ns.Flush();
            }
            catch (Exception ex)
            {
                LogManager.getInstance().logError("send error:" + strName + ":" + arg_strCmd, ex);
            }
        }

        public void shutdown()
        {
            m_tcp.Close();

        }

        public bool doProcess()
        {
            if (!m_tcp.Connected)
                return false;
            
            while (m_ns.DataAvailable)
            {
                m_bary[m_nIndex++] = (byte)m_ns.ReadByte();
                if (m_nIndex > 2 && m_bary[m_nIndex - 1] == 0x0A && m_bary[m_nIndex - 2] == 0x0D)
                    break;
                if (m_bary[m_nIndex - 1] == '$')
                {
                    m_nIndex = 0;
                }

            }

            m_nIndex = 0;
            
            return true;

        }
    }
}
